package com.eightywork.life.activity;

import java.util.List;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.Html;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import cn.jpush.android.api.JPushInterface;
import cn.sharesdk.framework.ShareSDK;

import com.eightywork.life.R;
import com.eightywork.life.fragment.CommunityFragment;
import com.eightywork.life.fragment.GroupFragment;
import com.eightywork.life.fragment.MapFragment;
import com.eightywork.life.fragment.NeighbourFragment;
import com.eightywork.life.fragment.SettingFragment;
import com.eightywork.life.fragment.SpaceFragment;
import com.eightywork.life.imageCache.ImageLoader;
import com.eightywork.life.model.Ad;
import com.eightywork.life.model.Space;
import com.eightywork.life.service.CacheService;
import com.eightywork.life.service.CpService;
import com.eightywork.life.service.DataService;
import com.eightywork.life.service.SpaceService;
import com.eightywork.life.util.AndroidUtil;
import com.eightywork.life.util.MyHttpException;
import com.eightywork.life.widget.ActionsContentView;
import com.umeng.analytics.MobclickAgent;

public class IndexActivity extends BaseActivity implements OnClickListener {
	private ActionsContentView viewActionsContentView;
	private int defaultSpace = 0;
	private Handler handler = new Handler();
	private String TAG = CommunityFragment.TAG;
	private TextView menu1, menu2, menu3, menu4, menu5, adText;
	private RelativeLayout rl_menu4;
	private ImageView adImage;
	private AsyncTask adTask, updateTokenTask, countTask;
	public static Button numBtn;
	private boolean isFromReceive;
	public static IndexActivity activity = null;

	@Override
	public void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		setContentView(R.layout.acitvity_index);
		activity = this;
		viewActionsContentView = (ActionsContentView) findViewById(R.id.actionsContentView);
		viewActionsContentView.setFadingEdgeLength(0);
		viewActionsContentView.setFadeValue(0);
		viewActionsContentView.setSwipingEdgeWidth(AndroidUtil.dpToPx(48, context));
		viewActionsContentView.setFlingDuration(900);
		defaultSpace = viewActionsContentView.getSpacingWidth();
		
		ShareSDK.initSDK(context);
		if (CacheService.isLogined()) {
		    JPushInterface.init(getApplicationContext());
		    String token = CacheService.getSpace().getUid();
		    JPushInterface.setAliasAndTags(context, token, null);
		    updateTokenTask = new  UpdateTokenTask(token).execute();		   
		}
		initView();
		initData();
		defaultShowFragment(TAG);
		
	}

	@Override
	public void onResume() {
		
		super.onResume();
		JPushInterface.onResume(this);
	    MobclickAgent.onResume(this);
	}
	
	@Override
	public void onPause() {
	    super.onPause();
		JPushInterface.onPause(this);
	    MobclickAgent.onPause(this);
	}

	@Override
	protected void onDestroy() {
		if (adTask != null) {
			adTask.cancel(true);
		} 
		if (updateTokenTask != null) {
			updateTokenTask.cancel(true);
		}
		if (countTask != null) {
			countTask.cancel(true);
		}
		ShareSDK.stopSDK(context);
		super.onDestroy();
	}

	public void defaultShowFragment(String tag) {
		Bundle b = getIntent().getExtras();
		if (b != null) {
			String sendTag = b.getString("default");
			if (sendTag != null) {
				TAG = sendTag;
			}
		}
		FragmentManager fm = getSupportFragmentManager();
		Fragment defaultFragment = findFragment(TAG);
		FragmentTransaction tr;
		tr = fm.beginTransaction();
		tr.add(R.id.content, defaultFragment, TAG);
		tr.commit();
	}

	@Override
	public void onClick(View v) {
		final String tag = (String) v.getTag();
		getIntent().removeExtra("uid");
		if (tag.equals(CommunityFragment.TAG) || checkLogin()) {
			viewActionsContentView.mContentScrollController.fling2(
					viewActionsContentView.getContentContainer().getScrollX(),
					AndroidUtil.dpToPx(64, context), 500, defaultSpace, true);
			// viewActionsContentView.showActions();
			handler.postDelayed(new Runnable() {
				@Override
				public void run() {
					FragmentManager fm = getSupportFragmentManager();
					FragmentTransaction tr = fm.beginTransaction();
					Fragment fragment = null;
					fragment = findFragment(tag);					  
					if (TAG != null) {
						final Fragment currentFragment = fm
								.findFragmentByTag(TAG);
						if (currentFragment != null && !TAG.equals(tag))
							tr.remove(currentFragment);
					}
					if (fragment.isAdded()) {
						tr.show(fragment);
					//	System.out.println("Space--index1-xiaoquid>" + CacheService.getSpace().getXiaoquid());
					} else {
						tr.add(R.id.content, fragment, tag);
					}
					TAG = tag;
					tr.commit();
					viewActionsContentView.showContent();
				}
			}, 510);
		}
		setSelected(v);
	}

	private void setSelected(View v) {
		menu1.setSelected(false);
		menu2.setSelected(false);
		menu3.setSelected(false);
	//	menu4.setSelected(false);
		rl_menu4.setSelected(false);
		menu5.setSelected(false);
		v.setSelected(true);
	}

	public Fragment findFragment(String tag) {
		FragmentManager fm = getSupportFragmentManager();
		Fragment foundFragMent = fm.findFragmentByTag(tag);
		if (foundFragMent == null) {
			if (tag.equals(CommunityFragment.TAG)) {
				foundFragMent = new CommunityFragment(context,
						viewActionsContentView);
			}
			if (tag.equals(GroupFragment.TAG)) {
				foundFragMent = new GroupFragment(context,
						viewActionsContentView);
			} else if (tag.equals(NeighbourFragment.TAG)) {
				foundFragMent = new NeighbourFragment(context,
						viewActionsContentView);
			} else if (tag.equals(SpaceFragment.TAG)) {
				foundFragMent = new SpaceFragment(context,
						viewActionsContentView);
			} else if (tag.equals(SettingFragment.TAG)) {
				foundFragMent = new SettingFragment(context,
						viewActionsContentView);
			} else if (tag.equals(MapFragment.TAG)) {
				foundFragMent = new MapFragment(context, viewActionsContentView);
			}
		} 
		return foundFragMent;
	}

	public void initView() {
		DisplayMetrics dm = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(dm);
		findViewById(R.id.header_logo).getLayoutParams().width = dm.widthPixels
				- defaultSpace;
		findViewById(R.id.ad_image).getLayoutParams().width = dm.widthPixels
				- defaultSpace;
		menu1 = (TextView) findViewById(R.id.menu1);
		menu1.setOnClickListener(this);
		menu1.setSelected(true);
		menu1.setTag(CommunityFragment.TAG);
		menu2 = (TextView) findViewById(R.id.menu2);
		menu2.setOnClickListener(this);
		menu2.setTag(GroupFragment.TAG);
		menu3 = (TextView) findViewById(R.id.menu3);
		menu3.setOnClickListener(this);
		menu3.setTag(NeighbourFragment.TAG);
		menu4 = (TextView) findViewById(R.id.menu4);
//		menu4.setOnClickListener(this);
//		menu4.setTag(SpaceFragment.TAG);
		rl_menu4 = (RelativeLayout) findViewById(R.id.rl_menu4);
		rl_menu4.setOnClickListener(this);
		rl_menu4.setTag(SpaceFragment.TAG);	
		menu5 = (TextView) findViewById(R.id.menu5);
		menu5.setOnClickListener(this);
		menu5.setTag(SettingFragment.TAG);
		numBtn = (Button) findViewById(R.id.num);

		adImage = (ImageView) findViewById(R.id.ad_image);
		adText = (TextView) findViewById(R.id.ad_text);
	}

	private void initData() {
		if (!CacheService.isLogined()) {
			menu1.setText(getIntent().getStringExtra("xiaoquname"));
	//		menu4.setVisibility(View.GONE);
			rl_menu4.setVisibility(View.GONE);
			findViewById(R.id.line4).setVisibility(View.GONE);
		} else {
			isFromReceive = getIntent().getBooleanExtra("isFromReceive", false);
			rl_menu4.setVisibility(View.VISIBLE);
			findViewById(R.id.line4).setVisibility(View.VISIBLE);
			menu1.setText(CacheService.getSpace().getXiaoquname());
			menu4.setText(CacheService.getSpace().getName());				
		}
		
	  //  adTask = new AdTask().execute();
	}
	
	 class UpdateTokenTask extends AsyncTask<Void, Void, String> {
		 String token;
		 public UpdateTokenTask(String token) {
			 this.token = token;
		 }
			@Override
			protected String doInBackground(Void... params) {
				try {
					SpaceService.updateToken(CacheService.getSpace().getUid(), token);
				} catch (MyHttpException e) {
					e.printStackTrace();
				}
				return null;
			}
	}	 
	
	class AdTask extends AsyncTask{
		List<Ad> adList = null;
		@Override
		protected Object doInBackground(Object... params) {
			String xiaoquid = getIntent().getStringExtra("xiaoquid");
			if (CacheService.isLogined()) {
				xiaoquid = CacheService.getSpace().getXiaoquid();			
			}
			try {
				
				adList = SpaceService.ad(xiaoquid);
			} catch (MyHttpException e) {
				showMessage(e.getErrorMessage());
			}
			return null;
		}
		@Override
		protected void onPostExecute(Object result) {
			if(result == null){
				if (adList != null && adList.size() > 0) {
					final Ad ad = adList.get(0);
		//			System.out.println("==========ad.getAdimage()=====" + ad.getAdimage());
					new ImageLoader(context).DisplayImage("http://www.gstatic.com/translate/intl/en/logo2.png", adImage, -1, 0, 0);
					adText.setText(ad.getAdname());
					adText.setBackgroundColor(Color.BLACK);
					adText.getBackground().setAlpha(200);
					adImage.setOnClickListener(new OnClickListener() {
						@Override
						public void onClick(View arg0) {
							Intent intent = new Intent(context,
									BrowserActivity.class);
		   				    intent.putExtra("idtype", "ad");
							intent.putExtra("url", ad.getAdlink());
							startActivity(intent);
						}
					});
				}			
			}
		}
	}

	/**
	 * 连续两次点击退出键，退出程序
	 */
	private long exitTime = 0;

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK
				&& event.getAction() == KeyEvent.ACTION_DOWN) {
			if ((System.currentTimeMillis() - exitTime) > 2000) {
				Toast.makeText(getApplicationContext(), "再按一次退出程序",
						Toast.LENGTH_SHORT).show();
				exitTime = System.currentTimeMillis();
				if (viewActionsContentView.isActionsShown()) {
					viewActionsContentView.showContent();
				}
			} else {
				finish();
			}
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}
}
